﻿using System;
using System.Web.Caching;
using System.Web;

namespace BAL
{
    public class CacheHelper
    {
        /// <summary>
        /// 刷新缓存
        /// </summary>
        /// <param name="CacheName">缓存名称（如不存在将创建）</param>
        /// <param name="CacheBody">缓存内容</param>
        /// <param name="ExpireTime">过期时间（分钟）</param>
        /// <param name="Timeouts">超时时间（分钟）</param>
        public static void Refurbish(string CacheName, object CacheBody, int ExpireTime, int Timeouts)
        {
            Cache cache1 = HttpRuntime.Cache;
            if (ExpireTime == 0)
            {
                cache1.Insert(CacheName, CacheBody, null, DateTime.MaxValue, TimeSpan.FromMinutes(Timeouts));
            }
            else
            {
                cache1.Insert(CacheName, CacheBody, null, DateTime.Now.AddMinutes(ExpireTime), TimeSpan.FromMinutes(Timeouts));
            }
        }

        /// <summary>
        /// 新建缓存
        /// </summary>
        /// <param name="CacheName">缓存名称（如已存在将跳过，不会更新）</param>
        /// <param name="CacheBody">缓存内容</param>
        /// <param name="ExpireTime">过期时间（分钟）</param>
        /// <param name="Timeouts">超时时间（分钟）</param>
        public static void Add(string CacheName, object CacheBody, int ExpireTime, int Timeouts)
        {
            Cache cache1 = HttpRuntime.Cache;
            if (cache1.Get(CacheName) == null)
            {
                Refurbish(CacheName, CacheBody, ExpireTime, Timeouts);
            }
        }

        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="CacheName">缓存名称</param>
        public static void Remove(string CacheName)
        {
            Cache cache1 = HttpRuntime.Cache;
            cache1.Remove(CacheName);
        }

        /// <summary>
        /// 缓存是否存在
        /// </summary>
        /// <param name="CacheName">缓存名称</param>
        /// <returns>如果存在返回true</returns>
        public static bool IsExist(string CacheName)
        {
            Cache cache1 = HttpRuntime.Cache;
            if (cache1[CacheName] == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 读缓存
        /// </summary>
        /// <param name="CacheName">缓存名称</param>
        /// <returns></returns>
        public static object GetCache(string CacheName)
        {
            Cache cache1 = HttpRuntime.Cache;
            return cache1.Get(CacheName);
        }
    }
}
